package com.graduate.cec.service;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.URLUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.graduate.cec.common.JsonPage;
import com.graduate.cec.common.ResponseCode;
import com.graduate.cec.exception.CecServiceException;
import com.graduate.cec.mapper.UserMapper;
import com.graduate.cec.mapper.UserRoleMapper;
import com.graduate.cec.pojo.dto.UserSimpleDTO;
import com.graduate.cec.pojo.dto.RegisterDTO;
import com.graduate.cec.pojo.entity.*;
import com.graduate.cec.pojo.entity.User;
import com.graduate.cec.pojo.vo.UserInfoVO;
import com.graduate.cec.pojo.vo.UserSimpleVO;
import com.graduate.cec.util.CopyUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;
import java.util.UUID;

@Service
@Slf4j
public class UserService {
    @Resource
    UserMapper userMapper;

    @Value("${kbs.jwt.secret-key}")
    private String secretKey;
    String dirPath = null;

    @Resource
    UserRoleMapper userRoleMapper;


    /****************        增      ******************************************************************/

    public Long register(RegisterDTO registerDTO) {
        if (userMapper.selectPhone(registerDTO.getPhone()) == 0) {
            User user = new User();
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

            user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
            user.setDescription("此人很懒没有简介");
            user.setAvatar("https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png");
            user.setGender("M");
            user.setPhone(registerDTO.getPhone());
            user.setIsEnable((byte) 1);

            int i = userMapper.insertSelective(user);
            log.info("注册的用户id:{}",user.getId());
            if(i == 0){
                throw new CecServiceException(ResponseCode.INSERT_INFO_ERROR,"注册失败!");
            }else{
                return user.getId();
            }

        }else{
            throw new CecServiceException(ResponseCode.INSERT_INFO_ERROR,"用户已存在!");
        }
    }


    /****************        删       ******************************************************************/
    //删除上传的图片
    public void removePicture(String pictureName) {
        System.out.println(pictureName);
        String[] split = pictureName.split("/");
        pictureName = split[split.length - 1];
        System.out.println(pictureName);
        String filePath = dirPath + "/" + pictureName;
        System.out.println(filePath);
        new File(filePath).delete();
    }

    /****************        改      ******************************************************************/



    public UserSimpleVO updateAvatar(User user){
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andIdEqualTo(user.getId());


        int i = userMapper.updateByExampleSelective(user, userExample);

        if(i == 0){
            throw new CecServiceException(ResponseCode.UPDATE_INFO_ERROR,"更新失败!");
        }

        UserSimpleVO userSimpleVO = selectSimplePersonal();
        return userSimpleVO;


    }

    //上传图片
    public String uploadPictures(MultipartFile picFile) throws Exception {
        String urlStr = URLUtil.getURL(FileUtil.file("picture")).toString();
        dirPath = urlStr.substring(urlStr.indexOf("cec"), urlStr.indexOf("target"));
        String prefix = urlStr.substring(6, urlStr.indexOf("cec"));
        dirPath += "picture/";
        dirPath = prefix + dirPath + "avatar";

        String fileName = picFile.getOriginalFilename();

        //得到后缀名 从最后一个.出现的位置截取到最后
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //得到唯一文件名 UUID.randomUUID()得到一个唯一标识符
        fileName = UUID.randomUUID() + suffix;
        log.info("fileName = " + fileName);
        //准备保存图片的文件夹路径
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        //得到文件的完整路径
        String filePath = dirPath + "/" + fileName;
        log.info("filePath = " + filePath);
        //把文件保存到此路径
        picFile.transferTo(new File(filePath));
        //"http://localhost:19090/picture/article/"
        return  "http://localhost:19090/picture/avatar/" + fileName;
    }

    public void updateInfo(User user){
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andIdEqualTo(user.getId());
        int i = userMapper.updateByExampleSelective(user, userExample);
        if(i == 0){
            throw new CecServiceException(ResponseCode.UPDATE_INFO_ERROR,"更新失败!");
        }
    }

    public void updateRole(Long id){
        UserRole userRole = new UserRole();

        userRole.setRoleId(4L);

        UserRoleExample userRoleExample = new UserRoleExample();
        UserRoleExample.Criteria criteria = userRoleExample.createCriteria();
        criteria.andUserIdEqualTo(id);
        int i = userRoleMapper.updateByExampleSelective(userRole, userRoleExample);

        if(i == 0){
            throw new CecServiceException(ResponseCode.UPDATE_INFO_ERROR,"更新失败!");
        }
    }





    /****************        查      ******************************************************************/


    public JsonPage<User> getListByExample(UserSimpleDTO userSimpleDTO){

        PageHelper.startPage(userSimpleDTO.getPageNum(), userSimpleDTO.getPageSize());

        UserExample userExample = new UserExample();
        if(!("".equals(userSimpleDTO.getNickname())) && userSimpleDTO.getNickname() != null){
            UserExample.Criteria criteria = userExample.createCriteria();
            criteria.andNicknameEqualTo(userSimpleDTO.getNickname());
        }


        List<User> users = userMapper.selectByExampleWithBLOBs(userExample);

        return JsonPage.restPage(new PageInfo<>(users));
    }

    public UserSimpleVO selectSimplePersonal(){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String phone = (String) principal;
        log.info("selectSimplePersonal phone:{}",phone);
        return userMapper.selectSimplePersonal(phone);
    }

    public UserInfoVO selectInfoByPhone(){
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String phone = (String) principal;
        log.info("selectInfoByPhone phone:{}",phone);
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria = userExample.createCriteria();
        criteria.andPhoneEqualTo(phone);

        List<User> users = userMapper.selectByExampleWithBLOBs(userExample);

        UserInfoVO copy = CopyUtil.copy(users.get(0), UserInfoVO.class);

        return copy;
    }



}
